
package lansaowucan

import com.surelution.lansao.wxmp.IdRefuser;
import com.surelution.lansao.WxRawMessage;
import com.surelution.lansao.WxRawUser;
import java.util.List;
import com.surelution.lansao.WxRawUser;
import com.surelution.lansao.Member;
import com.surelution.lansao.PartnerMember;
import com.surelution.lansao.crawler.ProcessHelper;



class CrawlerJob {
    static triggers = {
      simple name: 'mySimpleTrigger', startDelay: 10000, repeatInterval: 60000  
    }

    def execute() {
		def members = Member.findAllByFakeIdIsNull()
		def cri = PartnerMember.createCriteria()
		if(members && members.size > 0) {
			def pms = cri.list() {
				'in'('member', members)
				order('partner')
			}
			HashSet pmset = new HashSet()
			pmset.addAll(pms.collect {
				it.partner
			})
			def httpClient
			def users
			pmset.each {partner->
				httpClient = ProcessHelper.buildClient(partner.wxUsername, partner.wxPassword)
				users = ProcessHelper.getUsers(httpClient)
				users.each {u->
					def uDb = WxRawUser.findAllByFakeId(u.fakeId)
					if(!uDb) {
						u.save(flush:true)
						List<WxRawMessage> msgs = ProcessHelper.getUserMessages(httpClient, u.fakeId)
						if(msgs) {
							def msg = msgs.find {
								it.source == "biz" && it.content?.startsWith("感谢关注蓝嫂午餐直送")
							}
							if(msg) {
								def content = msg.content
								def sn = content.substring(content.indexOf("[") + 1, content.indexOf("]"))
								long lId = IdRefuser.reverseId(sn)
								def member = Member.get(lId)
								member.fakeId = u.fakeId
								member.nickName = u.nickName
								member.save(flush:true)
							}
						}
					}
				}
			}
			
		}
    }
}
